package com.earl.eatbao.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.earl.eatbao.commons.dao.BaseRepsitoty;
import com.earl.eatbao.commons.service.BaseServiceImpl;
import com.earl.eatbao.dao.UserDao;
import com.earl.eatbao.dao.UserRoleDao;
import com.earl.eatbao.dao.eatbao.UserInfoDao;
import com.earl.eatbao.domain.eatbao.UserInfo;
import com.earl.eatbao.domain.sercurity.Role;
import com.earl.eatbao.domain.sercurity.User;
import com.earl.eatbao.domain.sercurity.UserRole;
import com.earl.eatbao.exception.DomainSecurityException;
import com.earl.eatbao.service.UserService;
import com.earl.eatbao.service.VerifyCodeService;
import com.earl.eatbao.util.UpLoadFile;

@Service("userService")
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {

    private static Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Resource
    private UserDao userDao;
    
    @Resource
    private UserRoleDao userroleDao;

    @Resource
    private UserInfoDao userInfoDao;
    
    /**
     * 验证码服务
     */
    @Resource
    private VerifyCodeService verifyCodeService;

    @Value("#{public[hashIterations]}")
    private int hashIterations;
    
	@Override
	protected BaseRepsitoty<User, Long> getDao() {
		return userDao;
	}
    
    @Override
    public Boolean changePassword(Long id, String oldPassword, String newPassword) {
        logger.info("进入修改密码changePassword方法");
        Boolean result = false;
        User user = getDao().findOne(id);
        String oldPassword_Md5 = new SimpleHash("SHA-1", oldPassword,null,hashIterations).toString();
        String password = user.getPassword();
        if (password.equals(oldPassword_Md5)) {
            String newPassword_Md5 = new SimpleHash("SHA-1", newPassword,null,hashIterations).toString();
            user.setPassword(newPassword_Md5);
            userDao.save(user);
            result = true;
        } else {
            throw new DomainSecurityException("旧密码错误");
        }
        logger.info("退出修改密码changePassword方法");
        return result;
    }


    @Override
    public List<Role> findRole(Long userId) {
        return userDao.findRole(userId);
    }

    //TODO 用户权限发生改变的时候，后台自动重新登录系统
    @Override
    public void  doLogin(String username, String password) {
        logger.info("进入doLogin方法");
        String password_Md5 =new SimpleHash("SHA-1", password,null,hashIterations).toString();
        logger.info("password_Md5:" + password_Md5);
        SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
        logger.info("退出doLogin方法");
    }

    @Override
    public List<String> findRoleName(Long userId) {
        return userDao.findRoleName(userId);
    }

    @Override
    public List<String> findPrivilegeCode(long l) {
        return userDao.findPrivilegeCode(l);
    }

    @Override
    public User findOneByLoginId(String loginid) {
        
        User user = userDao.findUniqueByAccount(loginid);
        if (null == user) {
            return null;
        }
        return user;
    }

    @Override
    public Boolean registerAccount(String account, String password,String verifycode) {
        logger.info("进入用户注册registerAccount方法");
        //TODO session里面设置验证码
        boolean status = verifyCodeService.confirmVerifyCode(verifycode, account);
        Boolean result = false;
        if(!status){
        	throw new DomainSecurityException("验证码校验失败");
        }
        User tmpuser = userDao.findUniqueByAccount(account);
        if (tmpuser != null) {
            throw new DomainSecurityException("该账号已经被注册");
        } else {
            try {
            	User user = new User();
            	user.setAccount(account);
                String password_Md5 = new SimpleHash("SHA-1", password,null,hashIterations).toString();
                user.setPassword(password_Md5);
                user.setCreatedDate(new Date());
                user.setLastModifiedDate(new Date());
                User save = userDao.save(user);
                UserRole userrole = new UserRole();
                userrole.setUserId(save.getId());
                userrole.setRoleId(1L);//角色标号为1 ，基本用户权限
                userrole.setCreatedDate(new Date());
                userrole.setLastModifiedDate(new Date());
                userrole.setCreatedBy(save.getId().toString());
                userrole.setLastModifiedBy(save.getId().toString());
                userroleDao.save(userrole);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
                throw new DomainSecurityException("注册失败");
            }
        }
        logger.info("退出用户注册registerAccount方法");
        return  result;
    }

	/**
	 * 冻结用户
	 * 
	 * @param userId
	 */
    @Override
	public boolean takeBackUser(long userId){

        logger.info("<====== 进入takeBackUser:方法,{[userId]" + userId +" } ====");
        logger.info("==== 退出takeBackUser方法 返回值类型:{ boolean: } =======>");
        return changeUserEnable(userId, false);
	}

	@Override
	public UserInfo findUserInfo(Long userId) {
		// TODO Auto-generated method stub
		UserInfo userInfo = userInfoDao.findByUserId(userId);
		User user = userDao.findOne(userId);
		//TODO 聚合user 跟 userInfo 信息 构造新的vo对象返回
		return null;
	}

	@Override
	public boolean resetPassword(String account, String password, String verifyCode) {
		// TODO Auto-generated method stub
		
		Boolean confirmSuccess = verifyCodeService.confirmVerifyCode(verifyCode, account);
		
		if(!confirmSuccess){
			throw new DomainSecurityException("验证码校验失败");
		}
		User user = userDao.findUniqueByAccount(account);
		String password_Md5 = new SimpleHash("SHA-1", password,null,hashIterations).toString();
		user.setPassword(password_Md5);
		userDao.save(user);
		return false;
	}

    @Override
    public void unfreezeUser(Long userId) {
        logger.info("<====== 进入unfreezeUser:方法,{[userId] :" + userId + " } ====");
        changeUserEnable(userId, true);
        logger.info("==== 退出unfreezeUser方法 返回值类型:{ void: } =======>");

    }

    @Override
    public Boolean upLoadUserImage(MultipartFile file, Long userId) {
        logger.info("<====== 进入upLoadUserImage:方法,{[file, userId] :" + userId + " } ====");
        User user = userDao.findOne(userId);
        Boolean result = false;
	    if (null != user){
            String imagePath = UpLoadFile.saveFile(file, UpLoadFile.getUUID());
            if (null != imagePath) {
                user.setUserImage(imagePath);
                userDao.save(user);
                logger.info("==== 保存文件成功 ====>" + imagePath);
                result = true;
            }
        }
        logger.info("==== 退出upLoadUserImage方法 返回值类型:{Boolean:" + result + "} =======>");
        return result;
    }

    /**
     * 更改用户状态
     * @param userId
     * @param enable
     * @return Boolean
     */
    private Boolean changeUserEnable(Long userId, boolean enable) {

        User user = userDao.findOne(userId);
        if (null != user) {
            user.setEnable(enable);
            userDao.save(user);
            return true;
        } else {
        	throw new DomainSecurityException("不存在该用户");
        }
    }

}
